package com.lgh.ibs.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 常用方法
 * 
 */
public class Util {
	
	/**
	 * 将字符串中的\r\n替换成<br>
	 * 
	 * @param str
	 * @return
	 */
	public static String toJavaString(String str) {
		if (str == null) {
			return null;
		} else {
			str.trim();
			str = str.replaceAll("\n", "<br>");
			str = str.replaceAll("\r", "");
			str = str.replaceAll("\t", "");
			return str;
		}
	}
	
	/**
	 * 将字符串中的英文单引号替换成中文单引号
	 * 
	 * @param str
	 * @return
	 */
	public static String toAcute(String str) {
		if (str == null) {
			return null;
		} else {
			str.trim();
			str = str.replaceAll("'", "‘");
			return str;
		}
	}

	/**
	 * 转码
	 * @param str
	 * @return
	 */
	public static String getGBK(String str) {
		String re = null;
		try {
			re = new String(str.getBytes("ISO8859_1"), "GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return re;
	}

	/**
	 * 转码
	 * */
	public static String getUTF8(String str) {
		String re = null;
		try {
			re = new String(str.getBytes("ISO8859_1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return re;
	}
	
	public static String getUnicode(String sourceStr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sourceStr.length(); i++) {
            int ch = (int) sourceStr.charAt(i);
            if (ch > 255)
            	sb.append("\\u" + Integer.toHexString(ch));
            else
            	sb.append("\\u00" + Integer.toHexString(ch));
        }
        return sb.toString();
    }

	/**
	 * 对象是否为空（==null || "" || size()==0） 目前支持的对象有String, Collection, Object[]
	 * 
	 * @param obj
	 *            判断对象
	 * @return boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean isEmpty(Object obj) {

		if (null == obj)
			return true;

		if (obj instanceof String)
			return "".equals((String) obj);

		if (obj instanceof Object[])
			return ((Object[]) obj).length == 0;

		if (obj instanceof Collection) {
			Collection c = (Collection) obj;
			boolean re = c.isEmpty();
			if (!re && c.size() == 1 && null == c.toArray()[0])
				re = true;
			return re;
		}

		if (obj instanceof Map)
			return ((Map) obj).size() == 0;

		return false;
	}

	/**
	 * 清除list中重复的元素
	 * 
	 * @param list
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public static List noRepeat(List list) {
		if (null == list)
			return null;
		List<Object> re = new ArrayList<Object>();
		Iterator itr = list.iterator();
		while (itr.hasNext()) {
			Object obj = itr.next();
			if (!re.contains(obj))
				re.add(obj);
		}
		return re;
	}

	/**
	 * 将double值四舍五入为指定的位数
	 * 
	 * @param double1
	 *            double值
	 * @param digit
	 *            四舍五入到多少位
	 * @return Double
	 */
	public static Double getDecimal(double double1, int precision) {
		BigDecimal b = new BigDecimal(double1);

		return Double.valueOf(b.setScale(precision, BigDecimal.ROUND_HALF_UP)
				.doubleValue());
	}

	/**
	 * 计算资产cia值
	 * 
	 * @param ciac
	 * 
	 * @param ciai
	 * 
	 * @param ciaa
	 * 
	 * @return cia
	 * */
	public static double getCia(int ciac, int ciai, int ciaa) {

		double v_A = 1.6;
		double v_B = 0.7;
		double v_C = 0.7;

		double ciad = v_A * Math.pow(2, ciac) + v_B * Math.pow(2, ciai) + v_C
				* Math.pow(2, ciaa);

		ciad = (Math.log(ciad) / Math.log(2)) / 3;

		return ciad;
	}
	
	//=====================================================================
	/**
	 * 使用zip压缩文件
	 * @param inputFileName
	 * @param zipFileName
	 * @throws Exception
	 */
	public static void zip(String inputFileName, String zipFileName)
			throws Exception {
		zip(zipFileName, new File(inputFileName));
	}

	public static void zip(String zipFileName, File inputFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		zip(out, inputFile, "");
		// System.out.println("zip done");
		out.close();
	}

	public static void zip(ZipOutputStream out, File f, String base)
			throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			// System.out.println(base);
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
	
	/**
	 * 过滤危险字符
	 * @param str
	 * @return
	 */
	public static String doString(String str){
		str=str.replaceAll("&","&amp;");
		str=str.replaceAll("<","&lt;");
		str=str.replaceAll(">","&gt;");
		str=str.replaceAll("'","");
		str=str.replaceAll(";","");
		str=str.replaceAll("--","");
		str=str.replaceAll("/","");
		str=str.replaceAll("%","");
		return str.trim();
	}	
	
//	public static void executeCommand(String cmd) {
//		try {
//			Process p = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd });
//			p.waitFor();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
//
//	public static void sendSms(String loginName, String pwd, String to, String msg) {
//		System.out.println("Send sms to:" + to);
//		String cmd = "/usr/local/nagios/fetion20091117/fx/fetion --mobile=" + loginName + " --pwd=" + pwd + " --to="
//				+ to + " --msg-utf8=" + msg;
//		executeCommand(cmd);
//	}
	
	/**
     * 获取IP byte 字节
     */
    public static byte [] getIpByte(String ipAddress) {
        String [] ipStr = ipAddress.split("\\.");//以"."拆分字符串
        byte [] ipByte = new byte[ipStr.length];
        for(int i = 0 ; i < ipStr.length; i++) {
            // 进行byte转换后不是会有溢出吗？为什么溢出后还是可以正确运行？
            ipByte[i] = (byte)(Integer.parseInt(ipStr[i])&0xFF);//调整整数大小,byte的数值范围为-128~127
        } 
        return ipByte;
    }
 
    public static void main(String[] args) throws Exception {
    	String str = "你好";
    	String unicode = getUnicode(str);
    	
    	 new String(str.getBytes(str), "UTF-8"); 
    	String string = new String(unicode);
    	System.out.println(unicode); 
    	System.out.println(string); 
	}
    
}